package com.desidea.common
{
	
	import Modules.Login.LoginInfo;
	import Modules.NavigationInfo;
	
	import com.desidea.components.grid.SuperGrid;
	import com.desidea.components.menu.LeftMenu;
	import com.desidea.components.menu.TopMenu;
	import com.desidea.components.timeentry.TimeEntryControl;
	
	import flash.display.DisplayObject;
	import flash.external.ExternalInterface;
	import flash.filesystem.File;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.containers.Grid;
	import mx.containers.GridItem;
	import mx.containers.GridRow;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DateField;
	import mx.controls.Label;
	import mx.controls.RichTextEditor;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.UIComponent;
	import mx.utils.StringUtil;

	public class CommonClass
	{
		private static var _serviceUrl:String;
		private static var _updateConfig:File;
		private static var _userName:String;
		private static var _userId:String;
		private static var _userLoginInfo:LoginInfo;
		
		private static var _navigationXML:XML;
		private static var _loginXML:XML;
		
		private static var _globalConfigHelper:ConfigHelper;
		
		private static var _selectedMenuCode:String;
		private static var _topMenuCtl:TopMenu;
		private static var _leftMenuCtl:LeftMenu;
		private static var _ni:NavigationInfo;
		
		public function CommonClass()
		{
			//TODO: implement function
		}
		
		/********************************************************
		 * SERVICE-URL PROPERTY
		 * ******************************************************/
		public static function get ServiceURL():String{
			return _serviceUrl;
		}
		public static function set ServiceURL(value:String):void{
			_serviceUrl = value;
		}

		/********************************************************
		 * AUTOUPDATE CONFIG FILE
		 * ******************************************************/
		public static function get updateConfigFile():File{
			return _updateConfig;
		}
		public static function set updateConfigFile(value:File):void{
			_updateConfig = value;
		}

		/********************************************************
		 * LOGIN INFO PROPERTY
		 * ******************************************************/
		public static function get UserLoginInfo():LoginInfo{
			return _userLoginInfo;
		}
		public static function set UserLoginInfo(value:LoginInfo):void{
			_userLoginInfo = value;
		}

		/********************************************************
		 * USER NAME PROPERTY
		 * ******************************************************/
		public static function get UserName():String{
			return _userName;
		}
		public static function set UserName(value:String):void{
			_userName = value;
		}

		/********************************************************
		 * USERID PROPERTY
		 * ******************************************************/
		public static function get UserID():String{
			return _userId;
		}
		public static function set UserID(value:String):void{
			_userId = StringUtil.trim( value );
		}

		/********************************************************
		 * NavigationXML XML PROPERTY
		 * ******************************************************/
		public static function get NavigationXML():XML{
			return _navigationXML;
		}
		public static function set NavigationXML(value:XML):void{
			_navigationXML = value;
		}
		
		/********************************************************
		 * ALERTS XML PROPERTY
		 * ******************************************************/
		public static function get AuthenticatedLoginXML():XML{
			return _loginXML;
		}
		public static function set AuthenticatedLoginXML(value:XML):void{
			_loginXML = value;
		}

		/********************************************************
		 * GLOBAL CONFIG HELPER PROPERTY
		 * ******************************************************/
		public static function get GlobalConfig():ConfigHelper{
			return _globalConfigHelper;
		}
		public static function set GlobalConfig(configHelper:ConfigHelper):void{
			_globalConfigHelper = configHelper;
		}

		/********************************************************
		 * SELECT MENU CODE PROPERTY
		 * ******************************************************/
		public static function get SelectedMenuCode():String{
			return _selectedMenuCode;
		}
		public static function set SelectedMenuCode(selectedMenuCode:String):void{
			_selectedMenuCode = selectedMenuCode;
		}

		/********************************************************
		 * TOP MENU CTL PROPERTY
		 * ******************************************************/
		public static function get TopMenuControl():TopMenu{
			return _topMenuCtl;
		}
		public static function set TopMenuControl(value:TopMenu):void{
			_topMenuCtl = value;
		}

		/********************************************************
		 * LEFT MENU CTL PROPERTY
		 * ******************************************************/
		public static function get LeftMenuControl():LeftMenu{
			return _leftMenuCtl;
		}
		public static function set LeftMenuControl(value:LeftMenu):void{
			_leftMenuCtl = value;
		}

		/********************************************************
		 * NAVIGATION INFO PROPERTY
		 * ******************************************************/
		public static function get NavInfo():NavigationInfo{
			return _ni;
		}
		public static function set NavInfo(value:NavigationInfo):void{
			_ni = value;
		}

		/********************************************************
		 * QUERY STRING PARAMETER PROPERTY
		 * ******************************************************/
		public static function get QueryStringParameters():Dictionary{
			var _queryStringFromUrl:String = ExternalInterface.call("window.location.search.substring", 1);
			var _paramsFromUrl:Dictionary = new Dictionary();
			if(_queryStringFromUrl){
                var params:Array = _queryStringFromUrl.split('&');
                var length:uint = params.length;
 
                for (var i:uint=0,index:int=-1; i<length; i++)
                {
                    var kvPair:String = params[i];
                    if ((index = kvPair.indexOf("=")) > 0)
                    {
                        var key:String = kvPair.substring(0,index);
                        var value:String = kvPair.substring(index+1);
                        _paramsFromUrl[key.toLowerCase()] = value;
                    }
                }
            }
            return _paramsFromUrl;
		}

		/********************************************************
		 * GRID LAYOUT METHOD
		 * ******************************************************/
		public static function GetGridLayout(items:ArrayCollection, noOfColumns:int, arrHorizontalAlignment:Array=null):Grid{
			var rowIndex:int = 0;
			var colIndex:int = 0;
			
			var grid:Grid = new Grid();
			grid.percentWidth = 100;
			grid.setStyle("horizontalAlign","center");
			
			if(arrHorizontalAlignment == null || arrHorizontalAlignment.length != noOfColumns){
				arrHorizontalAlignment = new Array(noOfColumns);
				for(var i:int = 0;i<noOfColumns;i++){
					arrHorizontalAlignment[i] = "center"
				}
			}

			
			for(rowIndex=0;rowIndex<items.length;rowIndex+=noOfColumns){
				var row:GridRow = new GridRow();
				row.percentWidth = 100;
				for(colIndex=0;colIndex<noOfColumns;colIndex++){
					var gridItem:GridItem = new GridItem();
					gridItem.percentWidth = 100;
					gridItem.setStyle("horizontalAlign", arrHorizontalAlignment[colIndex]);
		
					if( (rowIndex+colIndex) < items.length) {
						gridItem.addChild( items.getItemAt(rowIndex + colIndex) as DisplayObject );
					}else{
						gridItem.addChild(new Canvas() );
					}
					row.addChild(gridItem);
				}
				grid.addChild(row);
			}
			return grid;	
		}
		
		/**
		 * Method to set the data in the Controls using the response XML
		 * UIComponent.automationName is used to get the tag name
		 * This method is used mainly in Detail Screens of Containers/Trailer/Person
		 * */
		public static function setDataOnComponents(obj:UIComponent, response:XML, decode:Boolean=false):void{
			if(obj is Label){
				(obj as Label).text = StringUtil.trim( response.elements(obj.automationName).toString() );
			}else if(obj is TextInput){
				if(decode){
					(obj as TextInput).text = Base64.decode(StringUtil.trim( response.elements(obj.automationName).toString() ));
				}else{
					(obj as TextInput).text = StringUtil.trim( response.elements(obj.automationName).toString() );
				}
			}else if(obj is TextArea){
				(obj as TextArea).text = StringUtil.trim( response.elements(obj.automationName).toString() );
			}else if(obj is DateField){
				(obj as DateField).selectedDate = DateField.stringToDate( StringUtil.trim( response.elements(obj.automationName).toString() ), "MM/DD/YYYY");
			}else if (obj is CheckBox){
				(obj as CheckBox).selected = (StringUtil.trim( String(response.elements(obj.automationName)) ) == "X");
			}else if (obj is ComboBox){
				var lst:XMLList = response.elements(obj.automationName).entry as XMLList;
				(obj as ComboBox).dataProvider = lst;
				(obj as ComboBox).selectedItem = (lst.(@selected=="true") as XMLList)[0] as XML;
				if ((obj as ComboBox).selectedItem == null) (obj as ComboBox).selectedIndex = 0;
			}else if (obj is TimeEntryControl){
				(obj as TimeEntryControl).setTime( StringUtil.trim( response.elements(obj.automationName).toString()) );
			}else if(obj is RichTextEditor){
				(obj as RichTextEditor).htmlText = StringUtil.trim( response.elements(obj.automationName).toString() );
			}
		}

		/**
		 * Method to prepare the post data string
		 * UIComponent.automationName is used to get the parameter name
		 * This method is used mainly in Detail Screens of Containers/Trailer/Person
		 * */
		public static function preparePostString(obj:UIComponent, encode:Boolean=false):String{
			var postStr:String = obj.automationName + "=";
			if(obj is Label){
				postStr += escape( StringUtil.trim( (obj as Label).text));
			}else if(obj is TextInput){
				if(encode){
					postStr += escape( Base64.encode(StringUtil.trim( (obj as TextInput).text)));
				}else{
					postStr += escape( StringUtil.trim( (obj as TextInput).text));
				}
			}else if(obj is TextArea){
				postStr += escape( StringUtil.trim( (obj as TextArea).text));
			}else if(obj is DateField){
				postStr += escape(DateField.dateToString( (obj as DateField).selectedDate, "MM/DD/YYYY") );
			}else if (obj is CheckBox){
				postStr += escape(StringUtil.trim( (obj as CheckBox).selected?"X":"" ));
			}else if (obj is ComboBox){
				postStr += ( (obj as ComboBox).selectedItem == null)? "" : escape((obj as ComboBox).selectedItem.@id);
			}else if (obj is TimeEntryControl){
				postStr += escape(format((obj as TimeEntryControl).getTime()));
			}else if(obj is RichTextEditor){
				postStr += escape( StringUtil.trim( (obj as RichTextEditor).htmlText));
			}
			return postStr;
		}

		public static function format(tm:String):String{
			var time:String = tm.substr(0,2) + ":" + tm.substr(2,2);
			return time;
		}
		
		public static function setColumnWidth(grid:SuperGrid, colIndex:int, colWidth:int, alignment:String = "left"):void{
			if(grid.GridComponent.columnCount > colIndex)	
				grid.GridComponent.columns[colIndex].width = colWidth;
				
				var col:DataGridColumn = grid.GridComponent.columns[colIndex];
				col.setStyle("textAlign", alignment);
		}

	}
}
